﻿using BLL.Base;
using CommandService;
using Entity;
using Entity.DbEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL.BarCode
{
    /// <summary>
    /// 存货裁剪逻辑方法
    /// </summary>
   public class ProductCutBLL: PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        OperateModel oper; 
        List<OperateModel> operList;
        public ProductCutBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            oper = new OperateModel();
        }
       /// <summary>
       /// 临时裁卷方案添加
       /// </summary>
       /// <param name="tempCode"></param>
       /// <param name="datas"></param>
       /// <returns></returns>
        public ReturnResult TempCutAdd(string tempCode,string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var dlist = (List<Dictionary<string, string>>)Tools.Cache.GetCache(tempCode);
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                string msg="";
                if (dlist == null || dlist.Count<1)
                {//没有数据直接添加
                    dlist = new List<Dictionary<string, string>>();
                    this.AddTempCut(json,ref dlist,ref msg);
                    if (!string.IsNullOrWhiteSpace(msg))
                    {
                        rsl.Message = msg;
                        return rsl;
                    }
                }
                else
                {
                    #region 存在数据
                    bool isHave = true;
                    for (int i = 0; i < dlist.Count; i++)
                    {
                        string dCode = string.Format("{0}-{1}-{2}-{3}-{4}", dlist[i]["proCode"].ToString(), dlist[i]["xilie"].ToString(), dlist[i]["spec"].ToString(), dlist[i]["company"].ToString(), dlist[i]["company"].ToString(), dlist[i]["sMeter"].ToString());//已存在的数据
                        string aCode = string.Format("{0}-{1}-{2}-{3}-{4}", json["proCode"].ToString(), json["xilie"].ToString(), json["spec"].ToString(), json["company"].ToString(), json["sMeter"].ToString());//即将要添加的数据
                        if (dCode == aCode)
                        {
                            isHave = false;
                            if (json.Property("cutNum") != null && json.Property("cutMethod") != null)
                            {//更改记录信息
                                dlist[i]["cutNum"] = json["cutNum"].ToString();
                                dlist[i]["cutMethod"] = json["cutMethod"].ToString();
                            }
                            break;
                        }

                    }
                    if (isHave)
                    {
                        this.AddTempCut(json, ref dlist,ref msg);
                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                            rsl.Message = msg;
                            return rsl;
                        }
                    }
                    #endregion
                }
                if (dlist!=null && dlist.Count > 0)
                {
                    Tools.Cache.SetCache(tempCode, dlist);
                }
          
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 将分切方案添加至内存
       /// </summary>
       /// <param name="json"></param>
       /// <param name="dlist"></param>
        private void AddTempCut(JObject json,ref List<Dictionary<string,string>> dlist,ref string msg)
        {
            #region 
            if (json.Property("cutNum") != null && !string.IsNullOrWhiteSpace(json["cutNum"].ToString()) && json["cutNum"].ToString() != "0" && json.Property("cutMethod") != null && !string.IsNullOrWhiteSpace(json["cutMethod"].ToString()))
            {//裁卷件数、裁卷方案且都存在内容，否则不进行录入操作
                string cutStr = json["cutMethod"].ToString().Replace("，", ",");
                var vArr = cutStr.Split(',');
                double fqhj = 0;
                foreach (string s in vArr)
                {
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        fqhj += double.Parse(s);
                    }
                }
                if (fqhj != double.Parse(json["sMeter"].ToString()))
                {
                   msg = "分切方案有误";
                   return;
                }
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["proCode"] = json["proCode"].ToString();//存货编码
                dic["spec"] = json["spec"].ToString();//规格
                dic["sMeter"] = json["sMeter"].ToString();//单卷米数
                dic["xilie"] = json["xilie"].ToString();//系列
                dic["company"] = json["company"].ToString();//客户
                dic["cutNum"] = json["cutNum"].ToString();//数量
                dic["cutMethod"] = cutStr;//分切方案
                dlist.Add(dic);
            }
            #endregion
        }
       /// <summary>
       /// 分切方案保存
       /// </summary>
       /// <param name="tempCode"></param>
       /// <returns></returns>
        public ReturnResult SaveCutInfo(string tempCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var dlist = (List<Dictionary<string, string>>)Tools.Cache.GetCache(tempCode);
                if (dlist == null || dlist.Count < 1)
                {
                    rsl.Message = "没有数据要保存";
                    return rsl;
                }
                else
                {
                    DbProductCutPlan cplan;
                    StringBuilder sb = new StringBuilder();
                    sb.Append("select * from pro_ProductCutPlan_info where isdel=0 and isFinish=0");
                    var pTable = cmd.GetDataTable(sb.ToString());
                    for (int i = 0; i < dlist.Count; i++)
                    {
                        //var dr = pTable.Select("customCode='" + dlist[i]["company"].ToString() + "' and sMeter='" + dlist[i]["sMeter"].ToString() + "' and cutPlan='" + dlist[i]["cutMethod"].ToString() + "' and xilie='" + dlist[i]["xilie"].ToString() + "' and proColor='" + dlist[i]["color"].ToString() + "' and spec='" + dlist[i]["spec"].ToString() + "'");
                     
                            #region 不存在数据添加 暂时不考虑分切方案合并的情况
                            cplan = new DbProductCutPlan();
                            cplan.cCode = getTimeString()+i.ToString();
                            cplan.createtime = getNow();
                            cplan.proCode = dlist[i]["proCode"].ToString();
                            cplan.createuser = userLogin.UserInfo().userCode;
                            cplan.customCode = dlist[i]["company"].ToString();
                            cplan.cutNum = dlist[i]["cutNum"].ToString();
                            cplan.spec = dlist[i]["spec"].ToString();
                            cplan.xilie = dlist[i]["xilie"].ToString();
                            cplan.cutPlan = dlist[i]["cutMethod"].ToString();
                            cplan.sMeter = dlist[i]["sMeter"].ToString();
                            cplan.isdel = 0;
                            cplan.memo = tempCode;
                            cplan.isFinish = 0;
                            oper = new OperateModel();
                            oper.Data = cplan;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                            #endregion
                    }
                    if (dlist.Count > 0)
                    {
                        rsl = cmd.MoreUpdate(operList);
                        if (rsl.Result)
                        {
                            Tools.Cache.RemoveAllCache(tempCode);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 
       /// </summary>
       /// <param name="condition"></param>
       /// <returns></returns>
       public ReturnResult GetPlanCutInfo(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_CutPlanInfo where isdel=0 and baseCode='"+ userLogin.UserInfo().baseCode +"'");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            sb.Append(obj.Name + "= '" + obj.Value.ToString() + "' ");
                        }
                    }
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 根据条件获取分切记录
       /// </summary>
       /// <param name="condition"></param>
       /// <returns></returns>
       public ReturnResult GetCutRecords(string condition)
       {
           rsl = new ReturnResult();
           try
           {
               StringBuilder sb = new StringBuilder();
               sb.Append("select r.*,u.userName from pro_ProductCutPlan_records r");
               sb.Append(" inner join sys_users_info u on r.createuser=u.userCode");
               sb.Append(" where 1=1 ");
               sb = CreateSelectCondition(sb,condition);
               var table = cmd.GetDataTable(sb.ToString());
               if (table.Rows.Count > 0)
               {
                   rsl.Data = cmd.TableToDictionary(table);
                   rsl.Result = true;
               }
           }
           catch (Exception ex)
           {
               rsl.Message = ex.Message;
           }
           return rsl;
       }
       /// <summary>
       /// 分切计划删除
       /// </summary>
       /// <param name="dataId">数据id</param>
       /// <returns></returns>
       public ReturnResult DelCutPlan(string dataId)
       {
           rsl = new ReturnResult();
           try
           {
               StringBuilder sb = new StringBuilder();
               DbProductCutPlan cplan = new DbProductCutPlan();
               cplan.id = int.Parse(dataId);
               cplan.isdel = 1;
               cplan.delDate = getNow();
               cplan.delUser = userLogin.UserInfo().userCode;
               oper = new OperateModel();
               oper.Data = cplan;
               oper.Types = OperateModel.OperateType.Edit;
               oper.Conditions = "id";
               rsl = cmd.Edit(oper);
           }
           catch (Exception ex)
           {
               rsl.Message = ex.Message;
           }
           return rsl;
       }
    }
}
